package cn.mrlong.base.permission

import android.content.pm.PackageManager
import androidx.fragment.app.Fragment

typealias PermissionCallback = (allGranted: Boolean, permissions: List<String>) -> Unit

class PermissionFragment : Fragment() {
    private val REQUEST_CODE_PERMISSION = 0x00099
    private var callback: PermissionCallback? = null

    /**
     * 请求运行时权限
     * @param cb 回调请求结果
     * @param permissions Array<out String> 权限数组
     */
    fun requestRunPermissions(cb: PermissionCallback, vararg permissions: String) {
        callback = cb
        requestPermissions(permissions, REQUEST_CODE_PERMISSION)
    }

    /**
     * 请求返回结果
     * @param requestCode Int 请求码
     * @param permissions Array<String> 权限
     * @param grantResults IntArray 请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            val deniedList = ArrayList<String>()
            for ((index, result) in grantResults.withIndex()) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    deniedList.add(permissions[index])
                }
            }
            val allGranted = deniedList.isEmpty()
            //对申请权限的结果进行回调
            callback?.let { it(allGranted, deniedList) }
        }
    }
}